package com.aliengen.thingple.driverapp.data.models;

import com.aliengen.thingple.driverapp.data.exception.InvalidTagException;
import com.aliengen.thingple.driverapp.network.api.models.Operator;

import java.util.HashMap;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class OperatorTag extends Tag {
    protected static HashMap<byte[], OperatorTag> operators = new HashMap<byte[], OperatorTag>();

    protected Boolean isAllowed = false;
    protected Operator operator;

    public static OperatorTag get(byte[] tag) throws InvalidTagException
    {
        if(operators.containsKey(tag))
        {
            return operators.get(tag);
        }

        OperatorTag o = new OperatorTag(tag);
        operators.put(tag, o);

        return o;
    }

    public OperatorTag(byte[] tag) throws InvalidTagException
    {
        super(tag);

        if(this.tagType != 0x01)
        {
            throw new InvalidTagException("Not operator tag! " + this.tagType + " size=" + tag.length);
        }

        // Read epc: 55 01 00 00 01 00 02 16 00 00 00 00 00 00 00 01
        this.operator = new Operator();
        this.operator.operator_id = ((b(12) & 0xFF) << 24) + ((b(13) & 0xFF) << 16) + ((b(14) & 0xFF) << 8) + (b(15) & 0xFF);
    }

    public Boolean isSynchronized() {
        return this.operator == null;
    }

    public int getOperatorId()
    {
        return this.operator.operator_id;
    }

    public void setAllowed(Boolean allowed)
    {
        this.isAllowed = allowed;
    }

    public Boolean isAllowed() {
        return this.isAllowed;
    }

    public Operator getOperator()
    {
        return this.operator;
    }

    public void setOperator(Operator operator)
    {
        this.operator = operator;
    }

    @Override
    public String toString() {
        return "Operator " + this.operator.operator_id;
    }
}
